<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\ContentRequest;
use App\Http\Resources\ContentResource;
use App\Models\Content;
use App\Models\User;
use App\Notifications\SystemNotify;
use Auth;
use Illuminate\Http\Request;

class ContentController extends Controller
{

    public function index()
    {
        return ContentResource::collection(Content::paginate(5));
    }


    public function store(ContentRequest $request, Content $content)
    {
        $content->fill($request->input())->save();
        $this->notify($content);
        return $this->message('文章添加成功');
    }


    public function show(Content $content)
    {
        Auth::user()->notify(new SystemNotify($content));
        return $content;
    }


    public function edit(Content $content)
    {
        //
    }


    public function update(ContentRequest $request, Content $content)
    {
        $content->update($request->input());
        return $this->message('修改成功');
    }

    public function destroy(Content $content)
    {
        $content->delete();
        return $this->message('文章删除成功');
    }


    public function fuzzy(Request $request)
    {
        return ContentResource::collection(Content::where('title', 'like', '%' . $request->keywords . '%')->paginate(5));
    }

    /**
     * 文章发布后，通知栏目的创建者
     * @param Content $content
     */
    protected function notify(Content $content)
    {
        $id = $content->category->user_id;
        $user = User::find($id);
        $user->notify(new SystemNotify($content));
    }
}
